//! # 网关认证授权模块
//!
//! 基于 rustcloud-security 的网关认证集成，提供网关特定的认证中间件和功能。
//!
//! ## 核心功能
//!
//! * **网关认证中间件** - 集成到网关请求处理流程
//! * **认证提供者扩展** - 基于 rustcloud-security 的认证实现
//! * **网关特定优化** - 缓存、性能优化等
//!
//! ## 使用示例
//!
//! ```rust
//! use rustcloud_gateway::auth::*;
//! use rustcloud_security::prelude::*;
//!
//! // 创建JWT认证提供者
//! let jwt_provider = JwtAuthProvider::new("secret_key").await?;
//!
//! // 认证请求
//! let context = AuthContext::from_request(&request);
//! let principal = jwt_provider.authenticate(&context).await?;
//!
//! // 授权检查
//! let resource = Resource::new("user-service", "/api/users", "GET");
//! let authorized = jwt_provider.authorize(&principal, &resource).await?;
//! ```

pub mod jwt;
pub mod oauth2;
pub mod rbac;
pub mod api_key;
pub mod providers;
pub mod middleware;

#[cfg(test)]
pub mod auth_comprehensive_tests;

use async_trait::async_trait;
use std::sync::Arc;

// 重新导出 rustcloud-security 的核心类型
pub use rustcloud_security::prelude::*;

// 引入网关核心接口
use crate::core::{
    Middleware, GatewayRequest, GatewayResponse, GatewayContext, GatewayResult, GatewayError, AuthInfo
};

// 网关特定的认证配置和扩展

// 网关特定的认证中间件和扩展功能

/// 网关认证配置
#[derive(Debug, Clone)]
pub struct GatewayAuthConfig {
    /// 是否启用认证
    pub enabled: bool,
    /// 认证提供者配置
    pub provider_config: AuthProviderConfig,
    /// 权限检查配置
    pub permission_config: PermissionConfig,
    /// 缓存配置
    pub cache_config: Option<CacheConfig>,
}

/// 认证提供者配置
#[derive(Debug, Clone)]
pub struct AuthProviderConfig {
    /// 默认认证提供者
    pub default_provider: String,
    /// 支持的认证方式
    pub enabled_providers: Vec<String>,
}

/// 权限检查配置
#[derive(Debug, Clone)]
pub struct PermissionConfig {
    /// 是否启用权限检查
    pub enabled: bool,
    /// 默认拒绝访问
    pub default_deny: bool,
    /// 公开路径（无需认证）
    pub public_paths: Vec<String>,
}

/// 缓存配置
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// 缓存过期时间（秒）
    pub ttl_seconds: u64,
    /// 最大缓存数量
    pub max_entries: usize,
}

// 网关特定的认证实现和扩展

/// 网关认证中间件
/// 
/// 集成 rustcloud-security 的认证功能到网关请求处理流程中

/// 认证配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    /// 是否启用认证
    pub enabled: bool,
    /// 默认认证提供者
    pub default_provider: String,
    /// 认证提供者配置
    pub providers: HashMap<String, ProviderConfig>,
    /// 白名单路径（不需要认证）
    pub whitelist_paths: Vec<String>,
    /// 权限检查配置
    pub permission_config: PermissionConfig,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_provider: "jwt".to_string(),
            providers: HashMap::new(),
            whitelist_paths: vec![
                "/health".to_string(),
                "/metrics".to_string(),
                "/ping".to_string(),
            ],
            permission_config: PermissionConfig::default(),
        }
    }
}

/// 提供者配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderConfig {
    /// 提供者类型
    pub provider_type: AuthProviderType,
    /// 配置参数
    pub config: HashMap<String, String>,
    /// 是否启用
    pub enabled: bool,
}

/// 权限配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionConfig {
    /// 是否启用权限检查
    pub enabled: bool,
    /// 权限检查模式
    pub mode: PermissionMode,
    /// 默认权限
    pub default_permissions: Vec<String>,
}

impl Default for PermissionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            mode: PermissionMode::Strict,
            default_permissions: Vec::new(),
        }
    }
}

/// 权限检查模式
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PermissionMode {
    /// 严格模式 - 必须明确授权
    Strict,
    /// 宽松模式 - 默认允许
    Permissive,
    /// 自定义模式
    Custom,
}

// 重新导出公共接口
pub use jwt::*;
pub use oauth2::*;
pub use rbac::*;
pub use api_key::*;
pub use providers::*;

/// 认证中间件适配器，将现有的AuthProvider适配到新的Middleware接口
pub struct AuthProviderMiddleware {
    provider: Arc<dyn AuthProvider>,
    config: AuthConfig,
    name: String,
}

impl AuthProviderMiddleware {
    pub fn new(provider: Arc<dyn AuthProvider>, config: AuthConfig) -> Self {
        let name = format!("Auth({})", provider.get_provider_name());
        Self { provider, config, name }
    }
    
    /// 检查路径是否在白名单中
    fn is_whitelisted(&self, path: &str) -> bool {
        self.config.whitelist_paths.iter().any(|whitelist_path| {
            // 支持简单的通配符匹配
            if whitelist_path.ends_with('*') {
                let prefix = &whitelist_path[..whitelist_path.len() - 1];
                path.starts_with(prefix)
            } else {
                path == whitelist_path
            }
        })
    }
    
    /// 从网关请求创建认证上下文
    fn create_auth_context(&self, request: &GatewayRequest) -> AuthContext {
        AuthContext::new(
            request.headers.clone(),
            request.method.to_string(),
            request.uri.to_string(),
            request.client_ip.clone()
        ).with_query_params(request.query_params.clone())
    }
    
    /// 从主体创建认证信息
    fn create_auth_info(&self, principal: &Principal) -> AuthInfo {
        AuthInfo {
            user_id: principal.id.clone(),
            username: Some(principal.name.clone()),
            roles: principal.roles.clone(),
            permissions: principal.permissions.clone(),
            auth_type: self.provider.get_provider_type().to_string(),
            attributes: principal.attributes.clone(),
        }
    }
    
    /// 创建访问资源
    fn create_resource(&self, request: &GatewayRequest) -> Resource {
        let service = request.target_service.clone().unwrap_or_else(|| "unknown".to_string());
        Resource::new(service, request.path.clone(), request.method.to_string())
    }
}

#[async_trait]
impl Middleware for AuthProviderMiddleware {
    async fn before_request(&self, request: GatewayRequest, mut context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
        // 检查是否启用认证
        if !self.config.enabled {
            return Ok(request);
        }
        
        // 检查白名单
        if self.is_whitelisted(&request.path) {
            return Ok(request);
        }
        
        // 创建认证上下文
        let auth_context = self.create_auth_context(&request);
        
        // 执行认证
        let principal = self.provider.authenticate(&auth_context).await
            .map_err(|e| {
                match e {
                    AuthError::AuthenticationFailed(msg) => GatewayError::authentication(msg),
                    AuthError::InvalidToken(msg) => GatewayError::authentication(format!("无效令牌: {}", msg)),
                    AuthError::TokenExpired => GatewayError::authentication("令牌已过期"),
                    AuthError::UnknownUser(user) => GatewayError::authentication(format!("未知用户: {}", user)),
                    _ => GatewayError::authentication("认证失败")
                }
            })?;
        
        // 检查主体是否过期
        if principal.is_expired() {
            return Err(GatewayError::authentication("认证信息已过期"));
        }
        
        // 执行授权检查
        if self.config.permission_config.enabled {
            let resource = self.create_resource(&request);
            let authorized = self.provider.authorize(&principal, &resource).await
                .map_err(|e| {
                    match e {
                        AuthError::AuthorizationFailed(msg) => GatewayError::authorization(msg),
                        AuthError::InsufficientPermissions { required, current: _ } => {
                            GatewayError::authorization(format!("权限不足，需要: {}", required))
                        },
                        _ => GatewayError::authorization("授权失败")
                    }
                })?;
            
            if !authorized {
                return Err(GatewayError::authorization("无权访问该资源"));
            }
        }
        
        // 将认证信息添加到上下文
        let auth_info = self.create_auth_info(&principal);
        // 注意：由于Arc<T>的不可变性，这里需要更复杂的处理
        // 在实际实现中，可能需要使用RefCell或其他方式来修改context
        
        Ok(request)
    }
    
    async fn after_response(&self, response: GatewayResponse, _context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        // 认证中间件通常不需要处理响应
        Ok(response)
    }
    
    fn name(&self) -> &str {
        &self.name
    }
    
    fn priority(&self) -> i32 {
        5 // 认证中间件应该有很高的优先级
    }
}

#[cfg(test)]
mod middleware_tests {
    use super::*;
    use crate::core::{GatewayRequest, GatewayContext};
    use axum::http::{Method, Uri, HeaderMap, HeaderValue, StatusCode};
    use std::sync::Arc;
    use tokio;

    // ==================== Mock 实现 ====================
    
    /// Mock 认证提供者，用于测试
    pub struct MockAuthProvider {
        pub should_authenticate: bool,
        pub should_authorize: bool,
        pub should_error: bool,
        pub token_expired: bool,
        pub provider_name: String,
        pub provider_type: AuthProviderType,
    }
    
    impl MockAuthProvider {
        pub fn new() -> Self {
            Self {
                should_authenticate: true,
                should_authorize: true,
                should_error: false,
                token_expired: false,
                provider_name: "mock".to_string(),
                provider_type: AuthProviderType::Custom("mock".to_string()),
            }
        }
        
        pub fn with_auth_failure(mut self) -> Self {
            self.should_authenticate = false;
            self
        }
        
        pub fn with_authz_failure(mut self) -> Self {
            self.should_authorize = false;
            self
        }
        
        pub fn with_error(mut self) -> Self {
            self.should_error = true;
            self
        }
        
        pub fn with_token_expired(mut self) -> Self {
            self.token_expired = true;
            self
        }
        
        pub fn with_provider_name(mut self, name: String) -> Self {
            self.provider_name = name;
            self
        }
    }
    
    #[async_trait]
    impl AuthProvider for MockAuthProvider {
        async fn authenticate(&self, context: &AuthContext) -> AuthResult<Principal> {
            if self.should_error {
                return Err(AuthError::InternalError("Mock error".to_string()));
            }
            
            if !self.should_authenticate {
                return Err(AuthError::AuthenticationFailed("认证失败".to_string()));
            }
            
            // 从Authorization头或API Key获取用户ID
            let user_id = if let Some(token) = context.get_bearer_token() {
                format!("user_{}", token)
            } else if let Some(api_key) = context.get_api_key() {
                format!("user_{}", api_key)
            } else {
                "anonymous".to_string()
            };
            
            let mut principal = Principal::new(
                user_id.clone(),
                format!("User {}", user_id),
                PrincipalType::User
            )
            .add_role("user".to_string())
            .add_permission("read:basic".to_string());
            
            // 如果设置了token过期，则创建过期的principal
            if self.token_expired {
                principal = principal.with_expiry(SystemTime::now() - Duration::from_secs(3600));
            }
            
            Ok(principal)
        }
        
        async fn authorize(&self, _principal: &Principal, _resource: &Resource) -> AuthResult<bool> {
            if self.should_error {
                return Err(AuthError::InternalError("Mock authz error".to_string()));
            }
            
            Ok(self.should_authorize)
        }
        
        fn get_provider_type(&self) -> AuthProviderType {
            self.provider_type.clone()
        }
        
        fn get_provider_name(&self) -> &str {
            &self.provider_name
        }
    }
    
    // ==================== 测试工具函数 ====================
    
    /// 创建测试用的GatewayRequest
    fn create_test_request(method: Method, path: &str) -> GatewayRequest {
        let uri: Uri = path.parse().unwrap_or_else(|_| Uri::from_static("/"));
        let mut request = GatewayRequest::new(method, uri);
        request.path = path.to_string();
        request.set_target_service("test-service".to_string());
        request
    }
    
    /// 创建带有Authorization头的测试请求
    fn create_test_request_with_auth(method: Method, path: &str, auth_header: &str) -> GatewayRequest {
        let mut request = create_test_request(method, path);
        request.add_header("authorization", auth_header);
        request
    }
    
    /// 创建带有API Key的测试请求
    fn create_test_request_with_api_key(method: Method, path: &str, api_key: &str) -> GatewayRequest {
        let mut request = create_test_request(method, path);
        request.add_header("x-api-key", api_key);
        request
    }
    
    /// 创建测试用的GatewayContext
    fn create_test_context() -> Arc<GatewayContext> {
        Arc::new(GatewayContext {
            request_id: "test-request-123".to_string(),
            auth_info: None,
            rate_limit_info: None,
            route_info: None,
            attributes: std::collections::HashMap::new(),
            start_time: SystemTime::now(),
        })
    }
    
    /// 创建默认的认证配置
    fn create_default_auth_config() -> AuthConfig {
        AuthConfig::default()
    }
    
    /// 创建启用权限检查的认证配置
    fn create_auth_config_with_permission_check() -> AuthConfig {
        let mut config = AuthConfig::default();
        config.permission_config.enabled = true;
        config
    }
    
    /// 创建带有白名单的认证配置
    fn create_auth_config_with_whitelist(whitelist: Vec<String>) -> AuthConfig {
        let mut config = AuthConfig::default();
        config.whitelist_paths = whitelist;
        config
    }
    
    // ==================== AuthProviderMiddleware 基础测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_creation() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        assert_eq!(middleware.name(), "Auth(mock)");
        assert_eq!(middleware.priority(), 5);
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_disabled() {
        let provider = Arc::new(MockAuthProvider::new());
        let mut config = create_default_auth_config();
        config.enabled = false;
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_whitelist() {
        let provider = Arc::new(MockAuthProvider::new().with_auth_failure());
        let config = create_auth_config_with_whitelist(vec![
            "/health".to_string(),
            "/api/public/*".to_string()
        ]);
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        // 测试完全匹配的白名单路径
        let request1 = create_test_request(Method::GET, "/health");
        let context1 = create_test_context();
        let result1 = middleware.before_request(request1, context1).await;
        assert!(result1.is_ok(), "Health endpoint should be whitelisted");
        
        // 测试通配符匹配的白名单路径
        let request2 = create_test_request(Method::GET, "/api/public/status");
        let context2 = create_test_context();
        let result2 = middleware.before_request(request2, context2).await;
        assert!(result2.is_ok(), "Public API should be whitelisted");
        
        // 测试非白名单路径应该进行认证
        let request3 = create_test_request(Method::GET, "/api/private");
        let context3 = create_test_context();
        let result3 = middleware.before_request(request3, context3).await;
        assert!(result3.is_err(), "Private API should require authentication");
    }
    
    // ==================== 认证测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_successful_authentication() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer valid_token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Valid authentication should succeed");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_authentication_failure() {
        let provider = Arc::new(MockAuthProvider::new().with_auth_failure());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer invalid_token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Invalid authentication should fail");
        
        let error = result.unwrap_err();
        assert!(matches!(error, crate::core::GatewayError::Authentication { .. }));
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_token_expired() {
        let provider = Arc::new(MockAuthProvider::new().with_token_expired());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer expired_token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Expired token should fail");
        
        let error = result.unwrap_err();
        assert!(matches!(error, crate::core::GatewayError::Authentication { .. }));
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_no_auth_header() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        // 由于没有认证信息，应该创建匿名用户
        assert!(result.is_ok(), "Anonymous user should be allowed");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_api_key_authentication() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_api_key(Method::GET, "/api/users", "sk_test_123");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "API key authentication should succeed");
    }
    
    // ==================== 授权测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_authorization_disabled() {
        let provider = Arc::new(MockAuthProvider::new().with_authz_failure());
        let mut config = create_default_auth_config();
        config.permission_config.enabled = false;
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer valid_token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Authorization disabled should allow access");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_authorization_success() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_auth_config_with_permission_check();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer valid_token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Valid authorization should succeed");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_authorization_failure() {
        let provider = Arc::new(MockAuthProvider::new().with_authz_failure());
        let config = create_auth_config_with_permission_check();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer valid_token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Authorization failure should be rejected");
        
        let error = result.unwrap_err();
        assert!(matches!(error, crate::core::GatewayError::Authorization { .. }));
    }
    
    // ==================== 错误处理测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_internal_error() {
        let provider = Arc::new(MockAuthProvider::new().with_error());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Internal error should be propagated");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_authorization_internal_error() {
        let provider = Arc::new(MockAuthProvider::new().with_error());
        let config = create_auth_config_with_permission_check();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer token");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Authorization internal error should be propagated");
    }
    
    // ==================== 上下文创建测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_create_auth_context() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let mut request = create_test_request(Method::POST, "/api/users");
        request.set_client_ip("192.168.1.100".to_string());
        request.query_params.insert("filter".to_string(), "active".to_string());
        
        let auth_context = middleware.create_auth_context(&request);
        
        assert_eq!(auth_context.method, "POST");
        assert_eq!(auth_context.remote_addr, Some("192.168.1.100".to_string()));
        assert_eq!(auth_context.query_params.get("filter"), Some(&"active".to_string()));
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_create_resource() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let request = create_test_request(Method::DELETE, "/api/users/123");
        let resource = middleware.create_resource(&request);
        
        assert_eq!(resource.service, "test-service");
        assert_eq!(resource.path, "/api/users/123");
        assert_eq!(resource.method, "DELETE");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_create_auth_info() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let principal = Principal::new(
            "user123".to_string(),
            "John Doe".to_string(),
            PrincipalType::User
        )
        .add_role("admin".to_string())
        .add_permission("write:users".to_string())
        .add_attribute("email".to_string(), "john@example.com".to_string());
        
        let auth_info = middleware.create_auth_info(&principal);
        
        assert_eq!(auth_info.user_id, "user123");
        assert_eq!(auth_info.username, Some("John Doe".to_string()));
        assert_eq!(auth_info.roles, vec!["admin".to_string()]);
        assert_eq!(auth_info.permissions, vec!["write:users".to_string()]);
        assert_eq!(auth_info.auth_type, "Custom(mock)");
        assert_eq!(auth_info.attributes.get("email"), Some(&"john@example.com".to_string()));
    }
    
    // ==================== 白名单路径检查测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_is_whitelisted() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_auth_config_with_whitelist(vec![
            "/health".to_string(),
            "/metrics".to_string(),
            "/api/public/*".to_string(),
            "/docs/*".to_string(),
        ]);
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        // 测试完全匹配
        assert!(middleware.is_whitelisted("/health"));
        assert!(middleware.is_whitelisted("/metrics"));
        
        // 测试通配符匹配
        assert!(middleware.is_whitelisted("/api/public/status"));
        assert!(middleware.is_whitelisted("/api/public/info/version"));
        assert!(middleware.is_whitelisted("/docs/"));
        assert!(middleware.is_whitelisted("/docs/api.html"));
        
        // 测试不匹配
        assert!(!middleware.is_whitelisted("/api/private/users"));
        assert!(!middleware.is_whitelisted("/admin"));
        assert!(!middleware.is_whitelisted("/health/check")); // 不是通配符
    }
    
    // ==================== 响应处理测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_after_response() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        let response = crate::core::GatewayResponse::new(StatusCode::OK);
        let context = create_test_context();
        
        let result = middleware.after_response(response, context).await;
        assert!(result.is_ok());
        
        let processed_response = result.unwrap();
        assert_eq!(processed_response.status, StatusCode::OK);
    }
    
    // ==================== 复杂场景测试 ====================
    
    #[tokio::test]
    async fn test_auth_provider_middleware_complex_scenario() {
        let provider = Arc::new(MockAuthProvider::new().with_provider_name("jwt".to_string()));
        let mut config = create_auth_config_with_permission_check();
        config.whitelist_paths = vec![
            "/health".to_string(),
            "/api/public/*".to_string(),
        ];
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        // 场景1：白名单路径，无需认证
        let request1 = create_test_request(Method::GET, "/health");
        let context1 = create_test_context();
        let result1 = middleware.before_request(request1, context1).await;
        assert!(result1.is_ok(), "Whitelisted path should bypass auth");
        
        // 场景2：公共API，无需认证
        let request2 = create_test_request(Method::GET, "/api/public/status");
        let context2 = create_test_context();
        let result2 = middleware.before_request(request2, context2).await;
        assert!(result2.is_ok(), "Public API should bypass auth");
        
        // 场景3：私有API，需要认证和授权
        let request3 = create_test_request_with_auth(Method::GET, "/api/users", "Bearer valid_token");
        let context3 = create_test_context();
        let result3 = middleware.before_request(request3, context3).await;
        assert!(result3.is_ok(), "Authenticated request should succeed");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_different_auth_methods() {
        let provider = Arc::new(MockAuthProvider::new());
        let config = create_default_auth_config();
        let middleware = AuthProviderMiddleware::new(provider, config);
        
        // 测试Bearer token认证
        let request1 = create_test_request_with_auth(Method::GET, "/api/users", "Bearer jwt_token_123");
        let context1 = create_test_context();
        let result1 = middleware.before_request(request1, context1).await;
        assert!(result1.is_ok(), "Bearer token should work");
        
        // 测试API Key认证
        let request2 = create_test_request_with_api_key(Method::GET, "/api/users", "sk_test_456");
        let context2 = create_test_context();
        let result2 = middleware.before_request(request2, context2).await;
        assert!(result2.is_ok(), "API Key should work");
    }
    
    #[tokio::test]
    async fn test_auth_provider_middleware_permission_modes() {
        let provider = Arc::new(MockAuthProvider::new());
        
        // 测试严格模式
        let mut strict_config = create_auth_config_with_permission_check();
        strict_config.permission_config.mode = PermissionMode::Strict;
        let strict_middleware = AuthProviderMiddleware::new(provider.clone(), strict_config);
        
        let request = create_test_request_with_auth(Method::GET, "/api/users", "Bearer token");
        let context = create_test_context();
        let result = strict_middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Strict mode should allow authorized access");
        
        // 测试宽松模式
        let mut permissive_config = create_auth_config_with_permission_check();
        permissive_config.permission_config.mode = PermissionMode::Permissive;
        let permissive_middleware = AuthProviderMiddleware::new(provider.clone(), permissive_config);
        
        let request2 = create_test_request_with_auth(Method::GET, "/api/admin", "Bearer token");
        let context2 = create_test_context();
        let result2 = permissive_middleware.before_request(request2, context2).await;
        assert!(result2.is_ok(), "Permissive mode should allow access");
    }
}

// 为AuthProviderType添加Display trait实现
impl std::fmt::Display for AuthProviderType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthProviderType::Jwt => write!(f, "JWT"),
            AuthProviderType::OAuth2 => write!(f, "OAuth2"),
            AuthProviderType::ApiKey => write!(f, "ApiKey"),
            AuthProviderType::Basic => write!(f, "Basic"),
            AuthProviderType::Custom(name) => write!(f, "Custom({})", name),
        }
    }
}